package com.controller;

import com.entity.FormIdInfo;
import com.entity.TemplateData;
import com.entity.Wxmsg;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.service.FromIdService;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/2/18 0018.
 */
@RequestMapping("/fromId")
@RestController
public class FromIdController {
    @Autowired
    private FromIdService service;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }


    @ApiOperation(value = "发送推送")
    @PostMapping(value = "/sendMsg")
    @ResponseBody
    public String sendMsg(String userId, String formId, Integer type) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + getAccess_token();
        String openId = service.findOpenId(userId);
//        String formId = selectFormService.findFormId(userId);
        Wxmsg wxMssVo = new Wxmsg();
        wxMssVo.setTouser(openId);//用户openid
        if (type == 1) {
            wxMssVo.setTemplate_id("zGj5FKZytGMUhfXxa6iAaSL9q9rYcnaqG0NPoW5-UA8");
        } else if (type == 2) {
            wxMssVo.setTemplate_id("TkRkREMC-s7zwnkWHS1ko8H6QiuwdyC98IzkIPlZ_N0");
        }
        wxMssVo.setForm_id(formId);//formid
        wxMssVo.setPage("pages/index/index");
        Map<String, TemplateData> map = null;

        Map<String, TemplateData> m = new HashMap<>(5);

        //keyword1：订单类型，keyword2：下单金额，keyword3：配送地址，keyword4：取件地址，keyword5备注
        //这里改模板的数据。
        TemplateData keyword1 = new TemplateData();
        TemplateData keyword2 = new TemplateData();
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = tempDate.format(new java.util.Date());
        if (type == 1) {
            keyword1.setValue("有老师申请了你");
            m.put("keyword1", keyword1);
            keyword2.setValue(time);
            m.put("keyword2", keyword2);
            wxMssVo.setData(m);
        } else if (type == 2) {
            keyword1.setValue("有学生预约了您");
            m.put("keyword1", keyword1);
            keyword2.setValue(time);
            m.put("keyword2", keyword2);
            wxMssVo.setData(m);
        }
        ResponseEntity<String> responseEntity =
                restTemplate().postForEntity(url, wxMssVo, String.class);
        System.out.println("dfa" + responseEntity.getBody());
        return responseEntity.getBody();
    }

    @ApiOperation(value = "新增formId")
    @PostMapping(value = "/insertFormId")
    @ResponseBody
    public int insertFormId(String userId, String formId) {
        if (formId == null) {
            return 0;
        } else {
            return service.insertFormId(userId, formId);
        }
    }

    @ApiOperation(value = "查询对方formId")
    @PostMapping(value = "/selectOhterFormId")
    @ResponseBody
    public List<FormIdInfo> selectOhterFormId(String userId) {
        List<FormIdInfo> formId = service.selectOhterFormId(userId);
        return formId;
    }


    @ApiOperation(value = "修改formId的失效时间")
    @PostMapping(value = "/updateFormId")
    @ResponseBody
    public int updateFormId(Integer id) {
        return service.updateFormId(id);
    }

    public static String getAccess_token() {
        HttpClient client;
        String apiurl = "https://api.weixin.qq.com/cgi-bin/token";
        String appId = "wx1a47bb9e4089c8e2";
        String secret = "6fc9a52136015e492b033df19e6f1885";
        String turl = String.format("%s?grant_type=client_credential&appid=%s&secret=%s", apiurl, appId, secret);
        client = new DefaultHttpClient();
        HttpGet get = new HttpGet(turl);
        JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
        String result = null;
        try {
            HttpResponse res = client.execute(get);
            String responseContent = null; // 响应内容
            HttpEntity entity = res.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
            // 将json字符串转换为json对象
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (json.get("errcode") != null) {// 错误时微信会返回错误码等信息，{"errcode":40013,"errmsg":"invalid
                    // appid"}
                } else {// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    result = json.get("access_token").getAsString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接 ,释放资源
            client.getConnectionManager().shutdown();
            return result;
        }
    }
}
